package org.dsapr.codegen.processor.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import org.dsapr.codegen.common.AutoGenerateService;
import org.dsapr.codegen.common.BaseGenerateProcessor;
import org.dsapr.codegen.common.CodeGenerateProcessor;
import org.dsapr.codegen.model.NameContext;
import org.springframework.stereotype.Service;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.io.File;
import java.lang.annotation.Annotation;
import java.nio.file.Path;
import java.nio.file.Paths;

@AutoService(value = CodeGenerateProcessor.class)
public class ServiceAutoGenerateProcessor extends BaseGenerateProcessor {
    private static final String CODEGEN_INFO = buildMessage();

    @Override
    public void generateClass(TypeElement typeElement, RoundEnvironment roundEnvironment) throws Exception {
        NameContext context = NameContext.builder().build(typeElement);
        TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(context.getServiceClassName())
                .addAnnotation(Service.class)
                .addJavadoc(CODEGEN_INFO)
                .addModifiers(Modifier.PUBLIC)
                .superclass(ParameterizedTypeName.get(ClassName.get(ServiceImpl.class),
                        ClassName.get(context.getRepositoryPackageName(), context.getRepositoryClassName()),
                        ClassName.get(context.getEntityPackageName(), context.getClassName())))
                .addSuperinterface(ClassName.get(context.getIServicePackageName(), context.getIServiceClassName()));

        Path srcPath = Paths.get(typeElement.getAnnotation(AutoGenerateService.class).sourcePath());
        File srcAbsoluteFile = srcPath.toFile().getAbsoluteFile();
        if (srcAbsoluteFile.exists()) {
            File sourceFile = new File(srcAbsoluteFile.getAbsolutePath(), context.getControllerClassName() + ".java");
            if (!sourceFile.exists()) {
                writeJavaFile(getPackage(typeElement), typeSpecBuilder.build(), srcAbsoluteFile.getAbsolutePath());
            }
        }
    }

    @Override
    public Class<? extends Annotation> getAnnotation() {
        return AutoGenerateService.class;
    }

    @Override
    public String getPackage(TypeElement typeElement) {
        return typeElement.getAnnotation(AutoGenerateService.class).packageName();
    }
}
